package Interface.Panel;

import Controller.*;
import DAOs.exceptions.NonexistentEntityException;
import Entity.User;
import Interface.Windows.MainWindow;
import java.util.logging.*;
import javax.persistence.EntityManagerFactory;
import javax.swing.*;

/**
 *
 * @author Esteban
 */
public class PanelUser extends javax.swing.JPanel {

    private UsersController usersController;
    private PeasantController peasantController;
    private InputController validator;
    private String unfilledFieldsMessage = "\"Por favor diligencie todos los campos marcados con *";
    private String passwordsMismatchMessage = "Los campos de contraseña no coinciden";
    private String SucessfullyCreatedMessage = "El empleado fue creado exitosamente";
    private String SucessfullyUpdatedMessage = "El empleado se ha actualizado exitosamente";
    private String alreadyExistMessage = "Ya existe un empleado con la misma cedula resgistrado en el sistema";
    private User currentUser;
    private MainWindow mainWindow;
    private EntityManagerFactory emf;

    /**
     * Creates new form PanelUser to Create a user
     */
    public PanelUser(EntityManagerFactory emf, MainWindow mainWindow) {
        usersController = new UsersController(emf);
        peasantController = new PeasantController(emf);
        validator = new InputController();
        this.mainWindow = mainWindow;
        this.emf = emf;
        initComponents();
    }

    //Creates new form PanelUser to Update a user
    public PanelUser(EntityManagerFactory emf, User currentUser, MainWindow mainWindow) {
        usersController = new UsersController(emf);
        peasantController = new PeasantController(emf);
        validator = new InputController();
        this.mainWindow = mainWindow;
        this.emf = emf;
        initComponents();
        if (currentUser != null) {
            this.currentUser = currentUser;
            this.cedulaField.setEnabled(false);
            this.cedulaField.setText(Integer.toString(currentUser.getCedula()));
            this.ageField.setText(currentUser.getAge());
            this.nameField.setText(currentUser.getName());
            this.lastnameField.setText(currentUser.getLastname());
            this.usernameField.setText(currentUser.getUserName());
            if (currentUser.getClass().getSimpleName().equals("Administrator")) {
                this.employeeRoleComboBox.setSelectedIndex(0);
            } else {
                if (currentUser.getClass().getSimpleName().equals("AdministrativeAssistant")) {
                    this.employeeRoleComboBox.setSelectedIndex(1);
                } else {
                    this.employeeRoleComboBox.setSelectedIndex(2);
                }
            }
            this.titleLabel.setText("Actualizar Datos Empleado");
            this.createButton.setText("Actualizar");
            this.createButton.setToolTipText("Actualizar Empleado");
        }
    }

    private void clearPanel() {
        this.cedulaField.setText("");
        this.ageField.setText("");
        this.nameField.setText("");
        this.lastnameField.setText("");
        this.usernameField.setText("");
        this.employeeRoleComboBox.setSelectedIndex(0);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bottomPanel = new javax.swing.JPanel();
        nameLabel = new javax.swing.JLabel();
        nameField = new javax.swing.JTextField();
        lastnameLabel = new javax.swing.JLabel();
        lastnameField = new javax.swing.JTextField();
        cedulaLabel = new javax.swing.JLabel();
        cedulaField = new javax.swing.JTextField();
        ageLabel = new javax.swing.JLabel();
        ageField = new javax.swing.JTextField();
        employeeRoleComboBox = new javax.swing.JComboBox();
        employeeRoleLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        passwordField = new javax.swing.JPasswordField();
        passwordConfirmationField = new javax.swing.JPasswordField();
        passwordConfirmationLabel = new javax.swing.JLabel();
        createButton = new javax.swing.JButton();
        usernameLabel = new javax.swing.JLabel();
        usernameField = new javax.swing.JTextField();
        topPanel = new javax.swing.JPanel();
        logoLabel = new javax.swing.JLabel();
        titleLabel = new javax.swing.JLabel();

        bottomPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Empleado"));

        nameLabel.setText("Nombres");

        nameField.setNextFocusableComponent(lastnameField);
        nameField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                nameFieldKeyTyped(evt);
            }
        });

        lastnameLabel.setText("Apellidos");

        lastnameField.setNextFocusableComponent(cedulaField);
        lastnameField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                lastnameFieldKeyTyped(evt);
            }
        });

        cedulaLabel.setText("Cedula");

        cedulaField.setNextFocusableComponent(ageField);
        cedulaField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                cedulaFieldKeyTyped(evt);
            }
        });

        ageLabel.setText("Edad");

        ageField.setNextFocusableComponent(usernameField);
        ageField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ageFieldKeyTyped(evt);
            }
        });

        employeeRoleComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Asistente", "Colaborador" }));

        employeeRoleLabel.setText("Cargo");

        passwordLabel.setText("Contraseña");

        passwordField.setNextFocusableComponent(passwordConfirmationField);
        passwordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                passwordFieldKeyTyped(evt);
            }
        });

        passwordConfirmationField.setNextFocusableComponent(createButton);
        passwordConfirmationField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                passwordConfirmationFieldKeyTyped(evt);
            }
        });

        passwordConfirmationLabel.setText("Confirmar Contraseña");

        createButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Interface/Resources/Save.png"))); // NOI18N
        createButton.setText("Crear");
        createButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                createButtonMouseClicked(evt);
            }
        });

        usernameLabel.setText("Nombre de usuario");

        usernameField.setNextFocusableComponent(passwordField);
        usernameField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                usernameFieldKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout bottomPanelLayout = new javax.swing.GroupLayout(bottomPanel);
        bottomPanel.setLayout(bottomPanelLayout);
        bottomPanelLayout.setHorizontalGroup(
            bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(bottomPanelLayout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(bottomPanelLayout.createSequentialGroup()
                        .addComponent(nameLabel)
                        .addGap(18, 18, 18)
                        .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(110, 110, 110)
                        .addComponent(usernameLabel)
                        .addGap(34, 34, 34)
                        .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(bottomPanelLayout.createSequentialGroup()
                        .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lastnameLabel)
                            .addComponent(cedulaLabel)
                            .addComponent(ageLabel))
                        .addGap(18, 18, 18)
                        .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(cedulaField, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                            .addComponent(lastnameField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(ageField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(110, 110, 110)
                        .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(passwordLabel)
                            .addComponent(passwordConfirmationLabel))
                        .addGap(18, 18, 18)
                        .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(passwordConfirmationField)
                            .addComponent(passwordField))))
                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(bottomPanelLayout.createSequentialGroup()
                        .addGap(89, 89, 89)
                        .addComponent(employeeRoleLabel)
                        .addGap(18, 18, 18)
                        .addComponent(employeeRoleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bottomPanelLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(createButton, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        bottomPanelLayout.setVerticalGroup(
            bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(bottomPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLabel)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(employeeRoleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(employeeRoleLabel)
                    .addComponent(usernameLabel)
                    .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(bottomPanelLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(createButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bottomPanelLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(bottomPanelLayout.createSequentialGroup()
                                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(lastnameLabel)
                                    .addComponent(lastnameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(cedulaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cedulaLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(ageField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(ageLabel)))
                            .addGroup(bottomPanelLayout.createSequentialGroup()
                                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(passwordLabel)
                                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(bottomPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(passwordConfirmationField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(passwordConfirmationLabel))))
                        .addContainerGap())))
        );

        logoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Interface/Resources/Empleado.png"))); // NOI18N

        titleLabel.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
        titleLabel.setText("Registro de Nuevo Empleado ULATA");

        javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
        topPanel.setLayout(topPanelLayout);
        topPanelLayout.setHorizontalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(logoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(titleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        topPanelLayout.setVerticalGroup(
            topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(logoLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)
            .addGroup(topPanelLayout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(topPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bottomPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(topPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bottomPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bottomPanel.getAccessibleContext().setAccessibleDescription("");
    }// </editor-fold>//GEN-END:initComponents

    private void createButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createButtonMouseClicked
        String password = String.valueOf(passwordField.getPassword());
        boolean updatedPassword = false;
        if (!nameField.getText().isEmpty() && !lastnameField.getText().isEmpty() && !cedulaField.getText().isEmpty()
                && !usernameField.getText().isEmpty() && !ageField.getText().isEmpty()) {
            if (validator.passwordsMatch(password, String.valueOf(passwordConfirmationField.getPassword()))) {
                if (currentUser == null) {
                    if (password.length() == 0) {
                        JOptionPane.showMessageDialog(new JFrame(), unfilledFieldsMessage, "Dialog", JOptionPane.ERROR_MESSAGE);
                    } else {
                        if((!usersController.Exist(Integer.parseInt(cedulaField.getText()))) &&(!peasantController.Exist(Integer.parseInt(cedulaField.getText()))) ){
                         usersController.createUser(nameField.getText(), lastnameField.getText(), usernameField.getText(), password, Integer.parseInt(cedulaField.getText()), ageField.getText(), employeeRoleComboBox.getSelectedItem().toString());
                        JOptionPane.showMessageDialog(new JFrame(), SucessfullyCreatedMessage, "Dialog", JOptionPane.INFORMATION_MESSAGE);
                        mainWindow.setPanel(new PanelUser(emf, mainWindow));   
                        }else{
                            JOptionPane.showMessageDialog(new JFrame(), alreadyExistMessage, "Dialog", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } else {
                    try {
                        if (!(password.length() == 0)) {
                            updatedPassword = true;
                            currentUser.setUserPassword(password);
                        }
                        currentUser.setName(nameField.getText());
                        currentUser.setLastname(lastnameField.getText());
                        currentUser.setCedula(Integer.parseInt(cedulaField.getText()));
                        currentUser.setAge(ageField.getText());
                        currentUser.setUserName(usernameField.getText());
                        currentUser = usersController.updateUser(currentUser, this.employeeRoleComboBox.getSelectedIndex(), updatedPassword);
                        JOptionPane.showMessageDialog(new JFrame(), SucessfullyUpdatedMessage, "Dialog", JOptionPane.INFORMATION_MESSAGE);
                        mainWindow.setPanel(new UsersListPanel(emf, mainWindow));
                    } catch (NonexistentEntityException ex) {
                        Logger.getLogger(PanelPeasantRegister.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        Logger.getLogger(PanelPeasantRegister.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(new JFrame(), passwordsMismatchMessage, "Dialog", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(new JFrame(), unfilledFieldsMessage, "Dialog", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_createButtonMouseClicked

    private void passwordConfirmationFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordConfirmationFieldKeyTyped
        validator.checkPasswordBR(evt);
    }//GEN-LAST:event_passwordConfirmationFieldKeyTyped

    private void passwordFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordFieldKeyTyped
        validator.checkPasswordBR(evt);
    }//GEN-LAST:event_passwordFieldKeyTyped

    private void ageFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ageFieldKeyTyped
        validator.checkAgeBR(evt);
    }//GEN-LAST:event_ageFieldKeyTyped

    private void cedulaFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cedulaFieldKeyTyped
        validator.checkCedulaBR(evt);
    }//GEN-LAST:event_cedulaFieldKeyTyped

    private void lastnameFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lastnameFieldKeyTyped
        validator.checkLastNameBR(evt);
    }//GEN-LAST:event_lastnameFieldKeyTyped

    private void nameFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nameFieldKeyTyped
        validator.checkNameBR(evt);
    }//GEN-LAST:event_nameFieldKeyTyped

    private void usernameFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_usernameFieldKeyTyped
        validator.checkUsernameBR(evt);
    }//GEN-LAST:event_usernameFieldKeyTyped
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField ageField;
    private javax.swing.JLabel ageLabel;
    private javax.swing.JPanel bottomPanel;
    private javax.swing.JTextField cedulaField;
    private javax.swing.JLabel cedulaLabel;
    private javax.swing.JButton createButton;
    private javax.swing.JComboBox employeeRoleComboBox;
    private javax.swing.JLabel employeeRoleLabel;
    private javax.swing.JTextField lastnameField;
    private javax.swing.JLabel lastnameLabel;
    private javax.swing.JLabel logoLabel;
    private javax.swing.JTextField nameField;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JPasswordField passwordConfirmationField;
    private javax.swing.JLabel passwordConfirmationLabel;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JLabel titleLabel;
    private javax.swing.JPanel topPanel;
    private javax.swing.JTextField usernameField;
    private javax.swing.JLabel usernameLabel;
    // End of variables declaration//GEN-END:variables
}
